package com.ruoyi.scheme.service.decision.Impl;

import com.ruoyi.scheme.pojo.Plant;
import com.ruoyi.scheme.pojo.PlatFormAndSlopeEntity;
import com.ruoyi.scheme.service.decision.Exp4jCalculationService;
import net.objecthunter.exp4j.Expression;
import net.objecthunter.exp4j.ExpressionBuilder;
import org.springframework.stereotype.Service;

@Service
public class Exp4jCalculationServiceImpl implements Exp4jCalculationService {
    @Override
    public Double calculatePlantDensity(Plant plant, PlatFormAndSlopeEntity platFormAndSlopeEntity) {
        // 检查输入参数是否为空
        if (plant == null || platFormAndSlopeEntity == null) {
            return null;
        }

        // 获取必要的参数
        Double ndvi = platFormAndSlopeEntity.getNdvi();
        Double rndvi = platFormAndSlopeEntity.getRndvi();
        Double area = platFormAndSlopeEntity.getArea();
        Double seedStandard = plant.getPlantDensity();

        // 参数校验
        if (ndvi == null || rndvi == null || area == null || seedStandard == null) {
            return null;
        }

        if (rndvi <= 0) {
            return null; // 避免除零错误
        }

        // 根据植物类型选择不同的计算公式
        if (plant.getPlantType().equals(1)) {
            // 草籽用量公式：(NDVI / RNDVI) × SeedStandard × Area
            String formula = "(NDVI / RNDVI) * SeedStandard * Area";

            try {
                Expression expression = new ExpressionBuilder(formula)
                        .variables("NDVI", "RNDVI", "SeedStandard", "Area")
                        .build()
                        .setVariable("NDVI", ndvi)
                        .setVariable("RNDVI", rndvi)
                        .setVariable("SeedStandard", seedStandard)
                        .setVariable("Area", area);

                double result = expression.evaluate();
                return Math.round(result * 100.0) / 100.0;

            } catch (Exception e) {
                System.err.println("草籽用量计算错误: " + e.getMessage());
                return null;
            }
        } else if (plant.getPlantType() .equals(2)) {
            // 种植数量公式：(NDVI / RNDVI) × PlantDensity × Area
            String formula = "(NDVI / RNDVI) * PlantDensity * Area";

            try {
                Expression expression = new ExpressionBuilder(formula)
                        .variables("NDVI", "RNDVI", "PlantDensity", "Area")
                        .build()
                        .setVariable("NDVI", ndvi)
                        .setVariable("RNDVI", rndvi)
                        .setVariable("PlantDensity", seedStandard)
                        .setVariable("Area", area);

                double result = expression.evaluate();
                return Math.round(result * 100.0) / 100.0;

            } catch (Exception e) {
                System.err.println("种植数量计算错误: " + e.getMessage());
                return null;
            }
        }

        // 默认情况返回null
        return null;
    }


}
